#include "version.hpp"
#include "db_manager.hpp"
#include <sstream>
#include <iomanip>

std::vector<Version> Version::getAll() {
    std::vector<Version> versions;
    auto* mysql = DBManager::getInstance().getConnection();
    
    if (!mysql) {
        throw std::runtime_error("无法获取数据库连接");
    }
    
    const char* query = "SELECT id, version FROM RouteVersion ORDER BY id DESC";
    if (mysql_query(mysql, query)) {
        throw std::runtime_error(std::string("查询失败: ") + mysql_error(mysql));
    }
    
    MYSQL_RES* result = mysql_store_result(mysql);
    if (!result) {
        throw std::runtime_error(std::string("存储结果失败: ") + mysql_error(mysql));
    }
    
    MYSQL_ROW row;
    while ((row = mysql_fetch_row(result))) {
        Version version;
        version.id = std::stoi(row[0]);
        version.version = std::stoi(row[1]);
        
        // 将版本号作为时间戳
        time_t timestamp = version.version;
        std::stringstream ss;
        ss << std::put_time(std::localtime(&timestamp), "%Y-%m-%d %H:%M:%S");
        version.time = ss.str();
        
        versions.push_back(version);
    }
    
    mysql_free_result(result);
    return versions;
}

bool Version::update() {
    auto* mysql = DBManager::getInstance().getConnection();
    
    if (!mysql) {
        throw std::runtime_error("无法获取数据库连接");
    }
    
    // 获取当前版本号
    const char* query = "SELECT version FROM RouteVersion ORDER BY id DESC LIMIT 1";
    if (mysql_query(mysql, query)) {
        throw std::runtime_error(std::string("查询失败: ") + mysql_error(mysql));
    }
    
    MYSQL_RES* result = mysql_store_result(mysql);
    if (!result) {
        throw std::runtime_error(std::string("存储结果失败: ") + mysql_error(mysql));
    }
    
    MYSQL_ROW row = mysql_fetch_row(result);
    if (!row) {
        mysql_free_result(result);
        throw std::runtime_error("未找到版本信息");
    }
    
    int current_version = std::stoi(row[0]);
    mysql_free_result(result);
    
    // 更新版本号
    char update_query[256];
    time_t current_time = std::time(nullptr);
    snprintf(update_query, sizeof(update_query),
             "INSERT INTO RouteVersion (version) VALUES (%ld)",
             current_time);
    
    if (mysql_query(mysql, update_query) != 0) {
        throw std::runtime_error(std::string("更新失败: ") + mysql_error(mysql));
    }
    
    return true;
} 